<template>
  <div>
    <div class="request" v-if="!requestAddShow && !requestDtlShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-if="route.name === 'Property'"
          v-hasPermi="['system:property:query']"
          class="btn search"
          @click="getRequestList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-if="route.name === 'PropertyCheck'"
          v-hasPermi="['system:propertyCheck:query']"
          class="btn search"
          @click="getRequestList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-if="route.name === 'Property'"
          v-hasPermi="['system:property:add']"
          class="btn search"
          @click="
            requestAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="intellectualPropertyCode">申请编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicationTime">申请日期</el-checkbox>
            </div>
            <div>
              <el-checkbox label="userName">经办人</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deptName">经办部门</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicationTypeName">申请类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="preApplicationName">预申请名称</el-checkbox>
            </div>
            <div>
              <el-checkbox label="propertyCheckStatusName">审核状态</el-checkbox>
            </div>
            <div>
              <el-checkbox label="nextNodeName">下步流程</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item">
          <el-input
            clearable
            v-model="params.intellectualPropertyCode"
            class="search-input"
            placeholder="请输入申请编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.userName"
            class="search-input"
            placeholder="请输入经办人"
          ></el-input>
        </div>
        <!-- <div class="search-item">
          <el-input
            clearable
            v-model="params.purchaseContractCode"
            class="search-input"
            placeholder="请输入关联合同"
          ></el-input>
        </div> -->

        <div class="search-item">
          <el-date-picker
            v-model="time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </div>
        <div class="search-item">
          <el-select
            v-model="params.applicationType"
            placeholder="请选择申请类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in applicationList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.propertyCheckStatus"
            placeholder="请选择审核状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in propertyCheckList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="requestList"
        border
        height="64vh"
        :header-cell-style="{ 'text-align': 'center' }"
        @sort-change="sortChange"
      >
        <!-- 操作模式 -->
        <el-table-column label="操作" width="150px">
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                v-if="
                  route.name === 'Property' &&
                  [0, 5, 6].includes(row.propertyCheckStatus)
                "
                v-hasPermi="['system:property:edit']"
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                v-if="route.name === 'Property'"
                v-hasPermi="['system:property:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-if="route.name === 'PropertyCheck'"
                v-hasPermi="['system:propertyCheck:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'PropertyCheck' &&
                  [1, 2].includes(row.propertyCheckStatus) &&
                  row.auditStatus == 1
                "
                v-hasPermi="['system:propertyCheck:list']"
                title="审核"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('check', row)"
              >
                <Checked />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'Property' &&
                  [0, 5].includes(row.propertyCheckStatus)
                "
                v-hasPermi="['system:property:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'PropertyCheck' &&
                  [0, 5].includes(row.propertyCheckStatus) &&
                  false
                "
                v-hasPermi="['system:propertyCheck:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
              <el-icon
                v-if="route.name === 'Property' && row.propertyCheckStatus == 1"
                title="撤销"
                color="#BBBBBB"
                class="table-icon"
                :size="20"
                v-hasPermi="['system:property:revoke']"
                @click="handleOperate('revoke', row)"
              >
                <!-- <Refresh /> -->
                <img
                  src="@/assets/icons/images/repeal.png"
                  style="width: 18px; height: 18px"
                />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="70"
          align="center"
        />
        <el-table-column
          label="申请编号" v-if="checkList.includes('intellectualPropertyCode')"
          prop="intellectualPropertyCode"
          :show-overflow-tooltip="true"
          min-width="120"
          sortable="custom"
        />

        <el-table-column
          label="申请日期" v-if="checkList.includes('applicationTime')"
          prop="applicationTime"
          :show-overflow-tooltip="true"
          width="180"
          sortable="custom"
        />
        <el-table-column
          label="经办人" v-if="checkList.includes('userName')"
          prop="userName"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          label="经办部门" v-if="checkList.includes('deptName')"
          prop="deptName"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          label="申请类型" v-if="checkList.includes('applicationTypeName')"
          prop="applicationTypeName"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          label="预申请名称" v-if="checkList.includes('preApplicationName')"
          prop="preApplicationName"
          :show-overflow-tooltip="true"
          min-width="120"
          sortable="custom"
        />
        <el-table-column label="关联合同" sortable="custom" v-if="checkList.includes('accountName')" prop="accountName" min-width="120">
          <template #default="{ row }">
            <el-dropdown
              v-if="row.synthesisConInfoDetailRespVos"
              trigger="hover"
              @command="handleStock"
            >
              <span
                class="el-dropdown-link"
                @click="handleProjectDetail(row.synthesisConInfoDetailRespVos)"
              >
                {{ row.synthesisConInfoDetailRespVos[0].synthesisContractName }}
                <el-icon class="el-icon--right"><CaretBottom /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <!-- <el-dropdown-item>
                    <div class="stock-list">
                      <span class="stock-item">关联合同名称</span>
                    </div>
                  </el-dropdown-item> -->
                  <div class="autodropp">
                    <el-dropdown-item
                      v-for="item in row.synthesisConInfoDetailRespVos"
                      :command="item.synthesisContractId"
                    >
                      <div class="stock-list">
                        <span class="stock-item">{{
                          item.synthesisContractName
                        }}</span>
                      </div>
                    </el-dropdown-item>
                  </div>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <span v-else>--</span>
          </template></el-table-column
        >
        <el-table-column
          label="审核状态" v-if="checkList.includes('propertyCheckStatusName')"
          prop="propertyCheckStatusName"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        >
          <template #default="{ row }">
            <span :style="getStatusColor(row.propertyCheckStatusName)">{{
              row.propertyCheckStatusName
            }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="下步流程" v-if="checkList.includes('nextNodeName')"
          prop="nextNodeName"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getRequestList"
      />
    </div>
    <RequestAdd
      ref="requestAddRef"
      v-if="requestAddShow"
      v-model:requestAddShow="requestAddShow"
      @refreshList="getRequestList"
      :pageType="pageType"
    />

    <RequestDtl
      ref="requestDtlRef"
      v-if="requestDtlShow"
      v-model:requestDtlShow="requestDtlShow"
      @refreshList="getRequestList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
import RequestAdd from "./requestAdd.vue";
import RequestDtl from "./dtl.vue";
import { getDictsApi } from "@/api/dict";
import {
  getPropertApi,
  checkPropertyApi,
  deletePropertyId,
  getPropertCheckListApi,
  saveCancel,
} from "@/api/serve/property";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
// 路由
const route = useRoute();
const router = useRouter();
//筛选时间
let time = ref([]);
// 搜索参数
const params = reactive({
  userName: "", // 	经办人
  intellectualPropertyCode: "", // 知识产权编号
  beginTime: "", //开始日期
  endTime: "", //结束日期
  applicationType: null, // 申请类型
  propertyCheckStatus: null, //审核状态
  // purchaseContractCode: "", // 合同编号
  pageNum: 1,
  pageSize: 50,
  sortField: "",
  sortOrder: "",
});
// 表格加载效果
const loading = ref(false);
// 列表数据
const requestList = ref([]);
// 审核状态列表
const propertyCheckList = ref([]);
// 申请类型列表
const applicationList = ref([]);
// 总数
const total = ref(0);
// 客户新增组件引用
const requestAddRef = ref(null);
// 客户新增组件显隐
const requestAddShow = ref(false);

// 客户查看组件引用
const requestDtlRef = ref(null);
// 客户查看组件显隐
const requestDtlShow = ref(false);
// 操作类型
const pageType = ref("");

const checkList = ref([
  "intellectualPropertyCode",
  "applicationTime",
  "userName",
  "deptName",
  "applicationTypeName",
  "preApplicationName",
  "propertyCheckStatusName",
  "nextNodeName",
]);

/**
 * @description: 复选框选中
 */
 const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: route.name === "Property" ?22 :23,
    titleField: str,
  });
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: route.name === "Property" ?22 :23,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 重置
 */
const handleRefresh = () => {
  time.value = [];
  Object.assign(params, {
    userName: "", // 	经办人
    intellectualPropertyCode: "", // 知识产权编号
    beginTime: "", //开始日期
    endTime: "", //结束日期
    applicationType: null, // 申请类型
    propertyCheckStatus: null, //审核状态
    // purchaseContractCode: "", // 合同编号
    pageNum: 1,
    pageSize: 50,
    sortField:"",
    sortOrder:"",
  });
  getRequestList();
};

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
 const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getRequestList();
};

/**
 * @description: 获取客户列表
 */
const getRequestList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    if (time.value != null && time.value.length > 0) {
      if (time.value[0] == time.value[1]) {
        params.beginTime = time.value[0] + " 00:00:00";
        params.endTime = time.value[1] + " 23:59:59";
      } else {
        params.beginTime = time.value[0];
        params.endTime = time.value[1];
      }
    } else {
      params.beginTime = "";
      params.endTime = "";
    }
    if (route.name === "Property") {
      params.auditType = 1;
      const res = await getPropertApi({ pageNum, pageSize }, params);
      requestList.value = res.rows;
      total.value = res.total;
    } else {
      params.auditType = 2;
      const res = await getPropertCheckListApi({ pageNum, pageSize }, params);
      requestList.value = res.rows;
      total.value = res.total;
    }
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "edit":
      pageType.value = type;
      requestAddShow.value = true;
      nextTick(() => {
        requestAddRef.value.handleDetailInfo(row.intellectualPropertyId);
      });
      break;
    case "detail":
      pageType.value = type;
      requestDtlShow.value = true;
      nextTick(() => {
        requestDtlRef.value.handleDetailInfo(row.intellectualPropertyId);
      });
      break;
    case "check":
      pageType.value = type;
      requestAddShow.value = true;
      nextTick(() => {
        requestAddRef.value.handleDetailInfo(row.intellectualPropertyId);
      });
      break;
    case "delete":
      ElMessageBox.confirm(
        "此操作将删除该知识产权申请信息，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          confirmButtonClass: "confirmBtnClass",
          cancelButtonClass: "cancelBtnClass",
          type: "warning",
        }
      )
        .then(async () => {
          const res = await deletePropertyId(row.intellectualPropertyId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getRequestList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    case "revoke":
      ElMessageBox.confirm(
        "此操作将撤销该该知识产权申请信息，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          confirmButtonClass: "confirmBtnClass",
          cancelButtonClass: "cancelBtnClass",
          type: "warning",
        }
      )
        .then(async () => {
          let params = {
            intellectualPropertyId: row.intellectualPropertyId,
            propertyCheckStatus: 5,
            contractType: null,
          };
          const res = await saveCancel(params);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getRequestList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};
/* 点击行内库存数据 */
const handleStock = async (command) => {
  const { href } = router.resolve({
    path: `/SealManage/serveContract`,
    query: { contractId: command },
  });
  window.open(href, "_blank");
};
/* 跳转项目详情 */
const handleProjectDetail = (row) => {
  const { href } = router.resolve({
    path: `/SealManage/serveContract`,
    query: { contractId: row[0].synthesisContractId },
  });
  window.open(href, "_blank");
};
/**
 * @description: 获取字典
 */
async function getDicts() {
  // 审核状态0:未提交,1:待审核,2:审核中,3:已通过,4:未通过,5:已撤销,6:已驳回
  await getDictsApi("erp_property_check_status").then((res) => {
    if (res.code === 200) {
      propertyCheckList.value = res.data;
    }
  });

  // 申请类型0：软件著作权；1：发明专利；2：实用新型专利；3：论文
  await getDictsApi("erp_application_type").then((res) => {
    if (res.code === 200) {
      applicationList.value = res.data;
    }
  });
}

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

onMounted(() => {
  getTableHeader();
  if (route.query?.businessId) {
    let applyId = route.query.businessId;
    if (
      route.query.checkStatus === "待审核" ||
      route.query.checkStatus === "审核中"
    ) {
      pageType.value = "check";
      requestAddShow.value = true;
      nextTick(() => {
        requestAddRef.value.handleDetailInfo(Number(applyId));
      });
    }
  }
  if (route.query?.myinfoId) {
    let applyId = route.query.myinfoId;
    pageType.value = "detail";
    requestDtlShow.value = true;
    nextTick(() => {
      requestDtlRef.value.handleDetailInfo(Number(applyId));
    });
  }
  getDicts();
  getRequestList();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.request {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
}
.autodropp {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
</style>
